
import * as Promise from 'promise'

import * as _ from 'lodash'

let fs = require('fs')

let path = require('path')

export default class ModuleLoader {

    private _options: {};

    constructor(opt: any) {
        this._options = _.cloneDeep(opt);
    }

    private loadHandler(modPath: string, files: []) {

        let tasks = [];
        files.forEach(function (file) {
            let handlerPath = path.join(modPath, file, "handler");
            let _files = fs.readdirSync(handlerPath);
            _files.forEach(function (_file) {
                tasks.push(new Promise(function (resovle, reject) {
                    let _modFile = path.join(handlerPath, _file);
                    console.log('loadHandlerController', _modFile); 
                    try {
                        require(_modFile);
                        resovle();
                    } catch (e) {
                        console.log(e);
                    }

                }))
            })
        })

        return Promise.all(tasks).then(function (result) { 
            return [];
        })
    }



    /**
     * 加载http请求接口
     * @param cb 
     */
    loadController(cb: Function) {

        let root = this._options['root'] || 'com/lovebugs/module';

        let modPath = path.resolve(root);

        let self = this;

        fs.readdir(modPath, function (err, files) {
            self.loadHandler(modPath, files).then(function () {
                //handler加载完成 
                cb && cb(null, { code: 200 });
            })
        });
    }

    /**
     * 加载模块
     * @param cb 
     */
    loadModule(cb: Function) {
        console.log('loadModule')
        cb && cb();
    }

    /**
     * 加载插件
     * @param cb 
     */
    loadPlugins(cb: Function) {
        console.log('loadPlugins')
        cb && cb();
    }
}